import { ref} from 'vue';
import type { diaryData } from "@/utils/interface";
import { getDiaryApi } from "@/api/diary_api";
import { useCode } from "@/hooks/codeHook";
import { weather } from '@/utils/data';
import { baseImgPath} from '@/utils/env'
const { tackleCode } = useCode();

export function useDiary() {

type getDiaryRequest = {
    pageSize: number;
    nowPage: number;
    searchTerm: string;
    count: boolean;
};

// 解析图片JSON数据
const parsePictures = (pictureStr: string | undefined) => {
    try {
        const pictures = JSON.parse(pictureStr || '[]')
        // urlArray.value = pictures.slice(0, 4).map((item: { url: string }) => `${baseImgPath}/${item.url}`);
        // console.log('urlArray', urlArray.value);
        return pictures.slice(0, 4);
    } catch (error) {
        console.error('解析图片数据失败:', error)
        return []
    }
}
// 解析图片数据
const getUrlList = (pictureStr: string | undefined) => {
    try {
        const pictures = JSON.parse(pictureStr || '[]')
        return pictures.slice(0, 4).map((item: { url: string }) => `${baseImgPath}/${item.url}`);
    } catch (error) {
        console.error('解析图片数据失败:', error)
        return []
    }
}


//获取天气url
const getWeatherUrl = (id: number) => {
    return weather[id].icon
}

//日记列表
const diaryList = ref<diaryData[]>([]);
//日记总数
const diaryCount = ref<number>(0);
 //获取日记
const getDiaryList = (request: getDiaryRequest) => {
    getDiaryApi(request).then((res) => {
        if (tackleCode(res.data.code)) {
            diaryCount.value = res.data.count;
            let data = res.data.data;
            diaryList.value = [...data];
            console.log('diaryList', diaryList.value);
        }
    });
};

const diaryDetail = ref<diaryData>({} as diaryData);
//获取某章卡片详情
const getDiaryDetail = (id: number) => {
   diaryDetail.value = diaryList.value.find(item => item.id === id) || ({} as diaryData);
   console.log('diaryDetail', diaryDetail.value);
}


return {
    getDiaryList,
    diaryList,
    diaryCount,
    getWeatherUrl,
    parsePictures,
    getUrlList,
    diaryDetail,
    getDiaryDetail

}


}